#coding=utf-8
import threading
from stscraper import NoLivePriceNowError,get_rtprice
from stutils import *
set_django_environ()
from stdj.stock.models import *
from hengpan import get_hp
import datetime
td = datetime.date.today().isoformat()

def get_start(code):
    try:
        a,b = get_rtprice(code)
        return a[-1]
    except NoLivePriceNowError,e:
        return None
    
tb_jump = ''' 
create table if not exists jump
(id integer primary key,
 date text not null,
 
 code text not null,
 name text not null,
 
 start real not null,
 jump real
 )
'''

exdays = ['2007-12-03',
 '2007-12-04',
 '2007-12-05',
 '2007-12-06',
 '2007-12-07',
 '2007-12-10',
 '2007-12-11',
 '2007-12-12',
 '2007-12-13',
 '2007-12-14',
 '2007-12-17',
 '2007-12-18',
 '2007-12-19',
 '2007-12-20',
 '2007-12-21',
 '2007-12-24',
 '2007-12-25',
 '2007-12-26',
 '2007-12-27',
 '2007-12-28',
 '2008-01-02',
 '2008-01-03',
 '2008-01-04',
 '2008-01-07',
 '2008-01-08']
 
def get_pre(exdate):
    i = exdays.index(exdate)
    return exdays[i-1]
    
def mysqljump2db(con, exdate):
    r = []
    
    pre = get_pre(exdate)
    cs = get_hp(con, pre)
    
    for c in cs:
        share = Share.objects.get(code=c)
        try:
            e = share.exday_set.get(date=exdate) 
        except Exday.DoesNotExist:
            continue
        p = e.price
        if p.jump and p.jump > 0 :r.append([share, p])
        
    c = con.cursor()    
    for d in r:
        s,p = d
        print s,p.jump
        c.execute('''insert into jump (date, code, name, start, jump) 
                     values (?,?,?,?,?)''',
                     (p.date, s.code, s.name, float(p.start), float(p.jump) ))
        
    con.commit()
               
def sohujump2db(con, share):
    s = get_start(share.code)
    if not s:return
    s = float(s)
    
    jump = None
    try: 
        preday_end = float(share.exday_set.latest('date').price.end)
        
        jump = float( todec( (s - preday_end)*100/preday_end, 2) )
    except Exday.DoesNotExist,e:
        pass
             
    c = con.cursor()
    c.execute('''insert into jump (code, name, date, start, jump)
                 values(?,?,?,?,?)
              ''',
              (share.code, share.name, td, s, jump)
              )
    con.commit()
    print 'Got 开盘价 of %s'%share
    
class GetStartThread(threading.Thread):
    def __init__(self, id, con, shares, start, end=None):
        threading.Thread.__init__(self)
        self.con = con
        self.id = id
        self.shares = shares
        
    def run(self):
        print  "线程%i启动."%self.id
        for s in self.shares:
            start2db(self.con, s)
        print  "线程%i结束."%self.id  

def get_jump(con, exdate, t=0):
    c = con.cursor()
    c.execute('select code,jump from jump where date=? and jump>=? order by jump desc', (exdate,t))
    r = c.fetchall()
    
    return r

if __name__ == '__main__':
    con = get_con()
    con.cursor().execute(tb_start)